import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/store/user'

// 创建axios实例
const request = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || '/api',
  timeout: 10000,
})

// 请求拦截器
request.interceptors.request.use(
  config => {
    const userStore = useUserStore()

    // 添加token到请求头
    if (userStore.token) {
      config.headers.Authorization = `Bearer ${userStore.token}`
    }

    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  response => {
    const { data } = response

    // 如果返回的是文件流，直接返回
    if (response.config.responseType === 'blob') {
      return data
    }

    // 统一处理业务错误
    if (data.code !== 200) {
      ElMessage.error(data.message || '请求失败')
      return Promise.reject(new Error(data.message || '请求失败'))
    }

    return data
  },
  error => {
    const { response } = error

    if (response) {
      switch (response.status) {
        case 401:
          // token过期，跳转到登录页
          const userStore = useUserStore()
          userStore.logoutAction()
          window.location.href = '/login'
          break
        case 403:
          ElMessage.error({ message: '没有权限访问' })
          break
        case 404:
          ElMessage.error({ message: '请求的资源不存在' })
          break
        case 500:
          ElMessage.error({ message: '服务器内部错误' })
          break
        default:
          ElMessage.error({ message: error.message || '请求失败' })
      }
    } else {
      ElMessage.error({ message: '网络连接失败' })
    }

    return Promise.reject(error)
  }
)

export default request
